package com.hhh.bigevent.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhh.bigevent.pojo.ArticleDO;
import com.hhh.bigevent.pojo.Result;
import com.hhh.bigevent.utils.ThreadLocalUtil;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hehehe
 * @since 2025-04-15
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    @PostMapping
    public Result<?> add(@RequestBody @Validated ArticleDO articleDO) {
        boolean b = articleDO.setCreateUser(ThreadLocalUtil.getUserId()).setCreateTime(LocalDateTime.now()).setUpdateTime(LocalDateTime.now()).insert();
        return Result.success(b);
    }

    @PutMapping
    public Result<?> update(@RequestBody @Validated(ArticleDO.Update.class) ArticleDO articleDO) {
        ArticleDO aDo = new ArticleDO().setId(articleDO.getId()).selectById();
        if (aDo == null) {
            return Result.error("操作失败！这个文章不存在！");
        }
        if (!aDo.getCreateUser().equals(ThreadLocalUtil.getUserId())) {
            return Result.error("操作失败！这个文章不属于你！");
        }
        boolean b = articleDO.setUpdateTime(LocalDateTime.now()).updateById();
        return Result.success(b);
    }

    @GetMapping("/detail")
    public Result<ArticleDO> detail(@RequestParam("id") Integer id) {
        ArticleDO articleDO = new ArticleDO().setId(id).selectById();
        return Result.success(articleDO);
    }

    @DeleteMapping
    public Result<?> delete(@RequestParam("id") Integer id) {
        ArticleDO aDo = new ArticleDO().setId(id).selectById();
        if (aDo == null) {
            return Result.error("操作失败！这个文章不存在！");
        }
        if (!aDo.getCreateUser().equals(ThreadLocalUtil.getUserId())) {
            return Result.error("操作失败！这个文章不属于你！");
        }
        boolean b = new ArticleDO().setId(id).deleteById();
        return Result.success(b);
    }

    @GetMapping
    public Result<?> page(@RequestParam("pageNum") Integer pageNum,
                          @RequestParam("pageSize") Integer pageSize,
                          @RequestParam(value = "categoryId", required = false) Integer categoryId,
                          @RequestParam(value = "state", required = false) String state) {
        Page<ArticleDO> articleDOPage = new ArticleDO().selectPage(new Page<>(pageNum, pageSize), Wrappers.lambdaQuery(ArticleDO.class)
                .eq(ArticleDO::getCreateUser, ThreadLocalUtil.getUserId())
                .eq(categoryId != null, ArticleDO::getCategoryId, categoryId)
                .eq(StringUtils.hasLength(state), ArticleDO::getState, state));
        return Result.success(articleDOPage);
    }
}
